package com.charon.auth.demo.intercept;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
  *@ClassName: TimeInterceptor
  *@Description: 时间拦截器（可以拿得到原始的Http请求的信息，也可以拿到处理的方法的信息，
  *                  但是拿不到方法参数的信息。）
  *@Author: Charon [248135724@qq.com]
  *@Date: 2019/1/13 0013 0:15
  *@Version: 1.0
  */
@Slf4j
@Component
public class TimeInterceptor implements HandlerInterceptor {

    //在进入控制器之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            log.info("拦截器开始：执行preHandler："+((HandlerMethod)handler).getBean().getClass().getName());
        }else{
            log.info("拦截器开始：执行preHandler："+handler.getClass().getName());
        }
        request.setAttribute("startTime",new Date().getTime());
        return true;
    }

    //在进入控制器返回之后调用，如果Conroller抛出异常，则不一定会被执行。
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //long startTime= (long) request.getAttribute("startTime");
        //log.info("拦截器结束时间postHandler"+(System.currentTimeMillis()-startTime));
    }

    //该方法最后调用 无论是否异常
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime= (long) request.getAttribute("startTime");
        log.info("拦截器结束：耗时："+(System.currentTimeMillis()-startTime));
    }
}
